﻿//全局变量
var table, myGrid, ised = "";

function UploadCard() {
    UploadToServer('coverpicture', 'Card', 'cardpic');
}

function UploadPloicy() {
    UploadToServer('policypic', 'Ploicy', 'policypicture');
}

function UploadToServer(id, path, id1) {
    $.ajaxFileUpload({
        url: 'UploadFile?path=' + path, //用于文件上传的服务器端请求地址
        secureuri: false, //是否需要安全协议，一般设置为false
        fileElementId: id, //文件上传域的ID
        dataType: 'text/html', //返回值类型 一般设置为json
        success: function (data, status) {
            if (data!='0') {
                $("#" + id1).val(data);
                var element = document.getElementById('carImg');
                element.src = "../../Resourse/" + data;
            } else {
                $.notify({
                    message: '<i class="fa fa-exclamation"></i> 请上传文件',
                    status: "danger",
                    pos: "bottom-right"
                });
            }
        }, error: function (data, status, e) {
            alert(e);
        }
    });
    return false;
}


$(document).ready(function () {
    GetMenuButtonList('btnOp');
    //#region datatable初始化及值绑定
    $.extend($.fn.dataTable.defaults, {
        dom: 'rt<"#dt-bottom.row"<"col-xs-2"l><"col-xs-7"p><"col-xs-3"i>>'
    });
    var scrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
    //适应窗口大小变化
    $(window).resize(function () {
        var newScrollY = document.body.clientHeight - 56 - 53 - 38 - 32 - 13 - 4;
        $('.dataTables_scrollBody').css('height', newScrollY);
    });
    myGrid = {
        id: 'dt_admin',
        isenable: false,//是否需要禁用启用按钮
        scrollY: scrollY,
        scrollX: true,
        paging: true,
        hasIndex: true,
        multiSelect: false,
        processing: true,
        serverSide: true,
        columns: [
                { data: "Row", title: "#" },
                { data: "code", title: "会员统一编码" },
                { data: "name", title: "姓名" },
                { data: "sex", title: "性别" },
                { data: "gradename", title: "会员等级" },
                { data: "cardno", title: "身份证号码" },
                { data: "mobile", title: "手机号码" },
                { data: "policynumber", title: "保单号码" },
                { data: "presentaddress", title: "现居地址" },
                { data: "emergencycontact", title: "紧急联系人" },
                { data: "emergencycontactrelation", title: "与紧急联系人关系" },
                { data: "emergencycontactmobile", title: "紧急联系人手机号" },
                { data: "policypicture", title: "保单图片" },
                { data: "cardpic", title: "身份证图片" },
                { data: "rescuecard", title: "救援卡卡号" },
                { data: "rescuestart", title: "救援生效起期" },
                { data: "rescueend", title: "救援生效止期" },
                { data: "resArea", title: "服务区域" }
        ],
        columnDefs: [{
            render: function (data, type, row) {
                return row.sex == 0 ? '男' : '女';
            },
            targets: [3]
        }, {
            render: function (data, type, row) {
                if (data.length > 0) {
                    return "<img src='../../Resourse/" + data + "' style='width:100px'/>";
                } else {
                    return "";
                }
            },
            targets: [13]
        }],
        order: [[1, 'desc']],
        data: {},
        ajax: function (data, callback, settings) {
            //封装请求参数
            var reUrl = 'GetMembers';
            var order = data.columns[data.order[0].column].data + " " + data.order[0].dir;
            var pagesize = data.length;
            var pageno = (data.start / data.length) + 1;
            //查询条件
            var searchData = { pagesize: pagesize, pageno: pageno, order: order, query: $('#query').val(), level: $('#levles').val() };
            //ajax请求数据
            $.ajax({
                type: "GET",
                url: reUrl,
                cache: false,//禁用缓存
                data: searchData,//传入组装的参数
                dataType: "json",
                //headers: param,//请求头参数
                success: function (result, status, xhr) {
                    //封装返回数据
                    var returnData = {};
                    returnData.draw = data.draw; //这里直接自行返回了draw计数器,应该由后台返回
                    returnData.recordsTotal = result.TotalCount;
                    total_curr = result.TotalCurr;
                    returnData.recordsFiltered = result.TotalCount; //后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = result.Entity; //返回的数据列表
                    //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                    //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                    callback(returnData);//将你的返回的data转为datatables能识别的数据格式作为参数返回ajax的callback回调中。
                }
            });
        }
    }
    table = DataBind(myGrid);
    //#endregion 
    $('#btnMembersSave').click(function () {
        AjaxSave();
    });

    $('#btnMembersPolicySave').click(function () {
        AjaxSavePolicy();
    });

    $('#btnMembersResSave').click(function () {
        AjaxSaveRes();
    });

    $('#datetimepicker_st,#datetimepicker_ed,#datetimepicker_start,#datetimepicker_end').datetimepicker({
        format: 'YYYY-MM-DD'
    });
    $('#btnInquire').click(function () {
        loadTableData();
    })
});
function GetResValues() {
    var obj = {};
    obj.memberid = $('#rmemberid').val();
    obj.rescuestart = $('#rescuestart').val();
    obj.rescueend = $('#rescueend').val();
    obj.servicearea = $('#servicearea').val();
    obj.rescuecard = $('#rescuecard').val();
    return obj;
}

function AjaxSaveRes() {
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveMemberRes?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetResValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#PolicyAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}

function GetPolicyValues() {
    var obj = {};
    obj.memberid = $('#memberid').val();
    obj.policynumber = $('#policynumber').val();
    obj.policypicture = $('#policypicture').val();
    obj.company = $('#company').val();
    obj.insureanceAgent = $('#insureanceAgent').val();
    return obj;
}

function AjaxSavePolicy() {
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveMemberPolicy?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetPolicyValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#PolicyAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}

//新增
var Btn_Add = function () {
    $('#title').text("会员录入");
    $('#code').val('-1');
    $('#id').val('-1');
    $("#name").val('');
    $("#sex").val('');
    $("#cardno").val('');
    $("#mobile").val('');
    $("#bloodType").val('');
    $("#emergencycontact").val('');
    $("#emergencycontactrelation").val('');
    $("#emergencycontactmobile").val('');
    $("#cardpic").val('');
    $("#point").val('');
    $("#presentaddress").val('');
    $("#illnesshistory").val('');
    $("#grade").val('');
    $("#receiveaddress").val('');
    var obj = document.getElementById('personCar');
    obj.style.display = "none";
    $('#InsuranceAccountAddModal').modal('show');
}
var Btn_AddPlo = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要录入保单的会员！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    $('#policytitle').text("录入保单");
    var seletedItem = table.rows('.selected').data()[0];
    $('#memberid').val(seletedItem.id);
    $('#policynumber').val('');
    $('#policypicture').val('');
    $('#company').val('');
    $('#insureanceAgent').val('');
    $('#PolicyAddModal').modal('show');
}
var Btn_AddRes = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要录入保单的会员！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    $('#restitle').text("录入救援卡");
    var seletedItem = table.rows('.selected').data()[0];
    $('#rmemberid').val(seletedItem.id);
    $('#rescuecard').val('');
    $('#rescuestart').val('');
    $('#rescueend').val('');
    $('#servicearea').val('');
    $('#RescueAddModal').modal('show');
}
//编辑
var Btn_Edit = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选中要编辑的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    var seletedItem = table.rows('.selected').data()[0];
    $('#title').text("会员编辑");
    $('#code').val(seletedItem.code);
    $('#id').val(seletedItem.id);
    $("#name").val(seletedItem.name);
    $("#sex").val(seletedItem.sex);
    $("#cardno").val(seletedItem.cardno);
    $("#mobile").val(seletedItem.mobile);
    $("#bloodType").val(seletedItem.bloodType);
    $("#emergencycontact").val(seletedItem.emergencycontact);
    $("#emergencycontactrelation").val(seletedItem.emergencycontactrelation);
    $("#emergencycontactmobile").val(seletedItem.emergencycontactmobile);
    $("#cardpic").val(seletedItem.cardpic);
    $("#point").val(seletedItem.point);
    $("#presentaddress").val(seletedItem.presentaddress);
    $("#illnesshistory").val(seletedItem.illnesshistory);
    $("#grade").val(seletedItem.grade);
    $("#receiveaddress").val(seletedItem.receiveaddress);
    var obj = document.getElementById('personCar');
    obj.style.display = "block";
    var element = document.getElementById('carImg');
    element.src = "../../Resourse/" + seletedItem.cardpic;
    $('#InsuranceAccountAddModal').modal('show');
}

//刷新datatable
function loadTableData() {
    table.ajax.reload();
}

function GetValues() {
    var obj = {};
    obj.id = $('#id').val();
    obj.code = $('#code').val();
    obj.name = $("#name").val();
    obj.sex = $("#sex").val();
    obj.cardno = $("#cardno").val();
    obj.mobile = $("#mobile").val();
    obj.bloodType = $("#bloodType").val();
    obj.emergencycontact = $("#emergencycontact").val();
    obj.emergencycontactrelation = $("#emergencycontactrelation").val();
    obj.emergencycontactmobile = $("#emergencycontactmobile").val();
    obj.cardpic = $("#cardpic").val();
    obj.point = $("#point").val();
    obj.presentaddress = $("#presentaddress").val();
    obj.illnesshistory = $("#illnesshistory").val();

    obj.grade = $("#grade").val();
    obj.receiveaddress = $("#receiveaddress").val();

    return obj;
}

function AjaxSave() {
    var obj = GetValues();
    var cd = /^[A-Za-z0-9]{18}/;// /(\d{18}) || (\d{17}[A-Z]{1})/;//定义身份证匹配算法
    var legalIdCard = $("#cardno").val();//获取前台界面字段值
    if (legalIdCard != null && legalIdCard != "") {//运用匹配方法直接判断
        if (cd.test(legalIdCard) == false) {
            alert("输入身份证号不合法!");
            $("#cardno").val("");//将前台输入值置为空
            return false;
        }
    }
    else if (legalIdCard == "") {
        alert("请输入身份证号!");
        $("#cardno").val("");//将前台输入值置为空
        return false;
    }

    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "SaveMember?t=" + new Date().getTime(),
        data: "{json:'" + $.toJSON(GetValues()) + "'}",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                $('#InsuranceAccountAddModal').modal('hide');
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}

//删除
var Btn_Delete = function () {
    if (table.rows('.selected').data().length == 0) {
        $.notify({
            message: '<i class="fa fa-bell-o"></i> 请选择要删除的数据！',
            status: "info",
            group: null,
            pos: "bottom-right"
        });
        return;
    }
    bconfirm("确定删除？", LogDelete);
}
//删除方法
function LogDelete() {
    var ids = [];
    for (var i = 0; i < table.rows('.selected').data().length; i++) {
        ids.push(table.rows('.selected').data()[i].code);
    }
    $.ajax({
        type: "post",
        contentType: "application/json;utf-8",
        url: "DeleteMembers?ids=" + ids.join() + "&t=" + new Date().getTime(),
        data: "",
        success: function (result) {
            result = eval('(' + result + ')');
            $.notify({
                message: '<i class="fa ' + (result.IsSucceed ? 'fa-check' : 'fa-exclamation') + '"></i> ' + result.Message,
                status: result.IsSucceed ? 'success' : "danger",
                pos: "bottom-right"
            });
            if (result.IsSucceed) {
                loadTableData(myGrid);
            }
            else {
                if (result.Entity != "" && result.Entity != null)
                    window.parent.location.href = result.Entity;
            }
        }
    });
}
